<?php

class Application_Model_Content extends Common_Model {

    public $tableName = 'Content';

    const S_NONE = 0;
    const S_PUBLISHED = 1;
    const S_UNPUBLISHED = 2;
    const S_TRASH = 3;
    const TYP_CONTENT = 0;
    const TYP_SLIDETOP = 1;
    const TYP_TEXTSHORT = 2;
    const BX_NULL = 'NULL';
    const BX_CENTER = 'center';
    const BX_HTOP = 'head_top';
    const BX_SLIDER = 'slider';
    const BX_LEFT = 'left';
    const BX_RIGHT = 'right';
    const BX_FOOT = 'foot';
    const STRIP_TAGS = '<p><a><div><em><strong><b><br><i><ul><li><img><span><ol><table><tr><td><th><h1><h2><h3><h4><h5><h6><hr>';

    public static $boxes = array(
        self::BX_NULL => 'none',
        self::BX_CENTER => 'center',
        self::BX_HTOP => 'nagl. top (disabled)',
        self::BX_SLIDER => 'element slider\'a',
        self::BX_LEFT => 'lewo',
        self::BX_RIGHT => 'prawo',
        self::BX_FOOT => 'stopka',
    );
    public static $status = array(
        self::S_NONE => 'none',
        self::S_PUBLISHED => 'opublikowane',
        self::S_UNPUBLISHED => 'odpublikowane',
        self::S_TRASH => 'kosz',
    );
    public static $typ = array(
        self::TYP_CONTENT => 'tresc',
        self::TYP_SLIDETOP => 'slider',
        self::TYP_TEXTSHORT => 'krótkie info',
    );

    public static function getTypOptions() {
        $h = '';
        foreach (self::$typ as $key => $typ) {
            $h .='<option label="-----" value="' . $key . '" >' . $typ . '</option>';
        }
        return $h;
    }

    public static function getBoxOptions() {
        $h = '';
        foreach (self::$boxes as $key => $typ) {
            $h .='<option label="-----" value="' . $key . '" >' . $typ . '</option>';
        }
        return $h;
    }

    public static function getStatusOptions() {
        $h = '';
        foreach (self::$status as $key => $typ) {
            $h .='<option label="-----" value="' . $key . '" >' . $typ . '</option>';
        }
        return $h;
    }

    /**
     * 
     * @return \Zend_Paginator_Adapter_DbSelect
     */
    public function getAdapterPagin($where = null, $order = null) {

        $select = $this->db->select()->from('v_content');

        if ($where != null)
            $select->where($where);
        if ($order != null)
            $select->order($order);
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);

        return $adapter;
    }

    /**
     * 
     * @return \Zend_Paginator_Adapter_DbSelect
     */
    public function getAdapterPaginForCategories($where = null, $order = null) {

        $select = $this->db
                ->select()
                ->from(
                array(
            'vc' => 'v_content'
                ), array(
            'vc.*',
            'GROUP_CONCAT(vc.categoryId SEPARATOR \' \') as categoryJoin',
                )
        )->group('vc.id');

        if ($where != null)
            $select->where($where);
        if ($order != null)
            $select->order($order);

        //var_dump($select.'');
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);

        return $adapter;
    }

    public function getForm() {

        $form = parent::getForm();

        $status = new Zend_Form_Element_Radio('status', array());
        $status->setLabel('Staus')
                ->addMultiOptions(array(
                    self::S_NONE => 'żaden',
                    self::S_PUBLISHED => 'opublikowane',
                    self::S_UNPUBLISHED => 'odpublikowane',
                    self::S_TRASH => 'kosz',
                ))
                ->setSeparator('-');
        $status->setValue(self::S_PUBLISHED);

        $addsOff = new Zend_Form_Element_Radio('addsOff', array());
        $addsOff->setLabel('Wyłącz reklamy')
                ->addMultiOptions(array(
                    0 => 'nie', 1 => 'tak',
                ))
                ->setSeparator('-');
        $addsOff->setValue(0);

        $typ = new Zend_Form_Element_Radio('typ', array());
        $typ->setLabel('Typ')
                ->addMultiOptions(self::$typ)
                ->setSeparator('-');
        $typ->setValue(self::TYP_CONTENT);

        $position = new Zend_Form_Element_Select('position', array());
        $position->setLabel('Kolejność:')
                ->addMultiOptions(array(
                    -6 => -6,
                    -5 => -5,
                    -4 => -4,
                    -3 => -3,
                    -2 => -2,
                    -1 => -1,
                    0 => 0,
                    1 => 1,
                    2 => 2,
                    3 => 3,
                    4 => 4,
                    5 => 5,
                    6 => 6,
                ))->setValue(0);

        $title = new Zend_Form_Element_Text('title', array(
                    'label' => 'Tytuł'
                ));
        $meta_keywords = new Zend_Form_Element_Text('meta_keywords', array(
                    'label' => 'Słowa kluczowe',
                    'size' => '90',
                ));

        $meta_description = new Zend_Form_Element_Textarea('meta_description', array(
                    'label' => 'Meta opis',
                    'rows' => '5',
                    'cols' => '70',
                ));
        $meta_robots = new Zend_Form_Element_Text('meta_robots', array(
                    'label' => 'Meta robots'
                ));
        $meta_robots->setValue('index,follow');
        $isDefault = new Zend_Form_Element_Checkbox('isDefault', array(
                    'label' => 'Jest domyślny?',
                ));
        $isHome = new Zend_Form_Element_Checkbox('isHome', array(
                    'label' => 'Strona główna',
                ));

        $rewrite = new Zend_Form_Element_Text('rewrite', array(
                    'label' => 'Rewrite URL(SEO)'
                ));
        $url = new Zend_Form_Element_Text('addUrl', array(
                    'label' => 'Adres reklamy',
                    'size' => '90'
                ));
        $short = new Zend_Form_Element_Textarea('short', array(
                    'label' => 'Któtki opis',
                    'class' => 'tinymce', //'markItUp',
                    'treść' => 'Krótka treść'
                ));
        $body = new Zend_Form_Element_Textarea('body', array(
                    'label' => 'Długi opis',
                    'class' => 'tinymce', //'markItUp',
                    'treść' => 'Treść'
                ));
        $userId = new Zend_Form_Element_Hidden('userId', array());

        $box = new Zend_Form_Element_Select('boxName', array(
                    'label' => 'Box'
                ));
        $box->addMultiOptions(self::$boxes);
        $boxTag = new Zend_Form_Element_Text('boxTag', array(
                    'label' => 'Wyrażenie [*]'
                ));

        $submit = new Zend_Form_Element_Submit('submitAndStay', array(
                    'label' => 'Wyślij i zostań',
                    'class' => 'ui-button round-all fr link-button'
                ));

        $submit->setDecorators(array('ViewHelper'));

        $catModel = new Application_Model_Categories();

        $categories = new Zend_Form_Element_Select('categories', array(
                    'size' => '10',
                ));
        $categories->setLabel('Kategorie:')
                ->addMultiOptions($catModel->getForOptions());

        $categoriesSelected = new Zend_Form_Element_Select('categoriesSelected', array(
                    'size' => '10',
                    'multiple' => 'multiple',
                ));
        $categoriesSelected->setLabel('Kategorie wybrane:')
                ->addMultiOptions(array(
                ))->setRegisterInArrayValidator(false);
        $btnGlowna = new Zend_Form_Element_Button('btnGlowna', array(
                    'label' => 'Ustaw jako główną',
                ));
        $idGlowna = new Zend_Form_Element_Hidden('idGlowna', array(
                    'label' => 'Główna',
                ));
        $form->addDisplayGroup(array(
            $categories, $categoriesSelected, $btnGlowna, $idGlowna
                ), 'gr-categorie');

        $form->getDisplayGroup('gr-submit')->addElement($submit);

        $form->addDisplayGroup(array(
            $status, $typ, $box, $boxTag, $rewrite, $position, $title, $short, $body,
            $meta_keywords, $meta_description, $meta_robots,
            $isDefault, $isHome, $userId
                ), 'gr-main');

        return $form;
    }

    public function getMainCategory($contentId) {
        $cats = new Application_Model_Categories();
        $item = $cats->getMainForContent($contentId);

        $cat = $item ? $cats->getById($item->categoryId) : null;

        return $cat ? $cat : null;
    }

    public function getCategories($contentId, $onlyId = false) {
        $categories = new Application_Model_ContentCategory();
        $r = $categories->fetchAll('contentId=' . $contentId);
        return $onlyId ? $this->getCol($r->toArray(), 'categoryId') : $r->toArray();
    }

    private function getCol($array, $colName) {
        $r = array();
        foreach ($array as $item) {
            $r[] = $item[$colName];
        }
        return $r;
    }

    public function getCmsList() {

        $rows = $this->db->query(
                        $this->db->select()
                                ->from('content', array('id', 'rewrite', 'title',))
                )->fetchAll();

        foreach ($rows as $key => $row) {
            $rows[$key]['link'] = $row['rewrite'] == "" ? 'default/index/content/id/' . $row['id'] : $row['rewrite'];
            $rows[$key]['label'] = $row['title'];
        }

        return $rows;
    }

    public function updateStaticRoutes() {

        $rows = $this->db->query(
                        $this->db->select()
                                ->from('content', array('id', 'rewrite',))
                                ->where('rewrite<>\'\'')
                )->fetchAll();

        $outPath = APPLICATION_PATH . '/configs/staticroutes.ini';
        $inPath = APPLICATION_PATH . '/configs/staticroutes-tpl.phtml';
        $tpl = file_get_contents($inPath);
        $out = '';
        file_put_contents($outPath, '');

        foreach ($rows as $row) {
            $out .=
                    preg_replace(
                            array(
                        '#{name}#',
                        '#{routeName}#',
                        '#{itemId}#',
                            ), array(
                        'r' . $row['id'],
                        $row['rewrite'],
                        $row['id']
                            ), $tpl) . PHP_EOL;
        }

        file_put_contents($outPath, $out);
    }

    public function buildWhereFromFiltered($params) {
        $p = array();

        foreach ($params as $name => $param) {
            if ($param == -1)
                continue;
            switch ($name) {
                case "id";
                    $p[] = 'id = ' . $param . '';
                    break;
                case "login";
                    $p[] = 'login like "' . $param . '%"';
                    break;
                case "createdod":
                    $p[] = 'created >= "' . $param . '"';
                    break;
                case "createddo":
                    $p[] = 'created <= "' . $param . ' 23:59:59"';
                    break;
                case "status":
                    $p[] = 'status = ' . $param . '';
                    break;
                case "typ":
                    $p[] = 'typ = ' . $param . '';
                    break;
                case "title":
                    $p[] = 'title like "' . $param . '%"';
                    break;
                case "box":
                    $p[] = 'boxName like "' . $param . '%"';
                    break;
            }
        }

        return count($p) > 0 ? '' . implode(' and ', $p) . '' : null;
    }

    public function buildOrderFromFiltered($params) {
        $p = array();

        foreach ($params as $name => $param) {
            if ($param == -1)
                continue;
            switch ($name) {
                case "id";
                    $p[] = 'id  ' . $param . '';
                    break;
                case "login";
                    $p[] = 'login  ' . $param . '';
                    break;
                case "created":
                    $p[] = 'created  ' . $param . '';
                    break;
                case "status":
                    $p[] = 'status  ' . $param . '';
                    break;
                case "typ":
                    $p[] = 'typ  ' . $param . '';
                    break;
                case "title":
                    $p[] = 'title ' . $param . '';
                    break;
            }
        }

        return count($p) > 0 ? $p : null;
    }

    public function getContent($where = null, $order = null) {
        $select = $this->db->select()->from('v_content');

        if ($where != null)
            $select->where($where);
        if ($order != null)
            $select->order($order);
        $result = $select->query();

        return $result ? $result->fetchAll(Zend_Db::FETCH_ASSOC) : array();
    }

    public function getContentByCategory($categoryId) {

        $categories = new Application_Model_Categories();
        $contentCategory = new Application_Model_ContentCategory();

        $to = $categories->getToHome($categoryId);
        $tos = self::category_array_return_col($to, 'id');
        
        $map = sizeof($tos) ==0 ? null : $contentCategory->getByCategory($tos);

        return $map;
    }

    public static function category_array_return_col($array, $name) {
        $r = array();

        foreach ($array as $item) {
            $r[] = $item[$name];
        }

        return $r;
    }

}

